angular.module('RDash', ['ui.bootstrap', 'ui.router', 'ngCookies', 'ngResource', 'ngWebSocket', 'simditor'])
    .constant('app', {
        global: {
            author: null,
            online: false,
            pre_url: null,
            cur_url: null
        },
        routes: [
            // {
            //     name: '权限管理',
            //     path: 'templates/roles.html',
            //     icon: 'menu-icon fa fa-gavel'
            // }
        ],
        /*
         * include包含的页面路径,
         * 作为首次切换到include子页面时提供的参数,
         * 将保存在cookie中,以在reload时能正确地找到对应的页面
         */
        include_path: null
    })
    .factory('cookieFactory', ['$cookies', '$cookieStore', function ($cookies, $cookieStore) {
        console.log('cookie-factory');

        var expiresTime = 15;
        var expiresDate = new Date();
        expiresDate.setDate(expiresDate.getDate() + expiresTime);

        var mine = {
            expiresDate: expiresDate,
            author: $cookies.getObject('author'),
            rememberMe: $cookies.get('rememberMe') == 'true'
        };
        // console.log(angular.toJson(mine, true));

        mine.setAuthor = function (author) {
            mine.author = author;
            $cookies.putObject('author', author, {'expires': mine.expiresDate});
        };

        mine.getAuthor = function () {
            return mine.author;
        };

        mine.setRememberMe = function (rememberMe) {
            mine.rememberMe = rememberMe;
            $cookies.put('rememberMe', rememberMe, {'expires': mine.expiresDate});
        };

        mine.getRememberMe = function () {
            return mine.rememberMe;
        };

        mine.setIncludePath = function (include_path) {
            $cookieStore.put('include_path', include_path);
        };

        mine.getIncludePath = function () {
            return $cookieStore.get('include_path');
        };

        mine.setBombAttrs = function (bombAttrs) {
            $cookieStore.put("bombAttrs", bombAttrs);
        };

        mine.getBombAttrs = function () {
            return $cookieStore.get("bombAttrs");
        };

        mine.putOToast = function (oToast) {
            var oToasts = mine.getOToasts();
            oToasts.push(oToast);
            $cookieStore.put('oToasts', oToasts);
        };

        mine.setOToasts = function (oToasts) {
            $cookieStore.put('oToasts', oToasts);
        };

        mine.getOToasts = function () {
            var oToasts = $cookieStore.get('oToasts');
            if (oToasts == null) {
                oToasts = [];
            }
            return oToasts;
        };

        return mine;
    }])
    .service('restService', ['$resource', function ($resource) {
        console.log('rest-service');

        this.root = '/admin/';

        this.create = function (url) {
            return this.root + url;
        };

        this.api = {
            index: $resource(this.create('index/:ID/:OP')),
            user: $resource(this.create('user/:ID/:OP')),
            authorize: $resource(this.create('authorize/:ID/:OP')),
            log: $resource(this.create('log/:ID/:OP')),
            bomb: $resource(this.create('bomb/:ID/')),
            notification: $resource(this.create("notification/:ID")),
            pushLink: $resource(this.create("pushLink/:ID")),
            statistics: $resource(this.create("statistics/:ID")),
            ranking: $resource(this.create("ranking/:ID"))
        };
    }])
    .service('minaService', ['$websocket', function ($websocket) {
        console.log('mina-service');

        var client = null;

        this.connect = function () {
            console.log('connect');
            client = $websocket('ws://127.0.0.1:8008');

            client.onOpen(function () {
                console.log("onOpen...");
            });
            client.onMessage(function (info) {
                console.log("onInfo... " + angular.toJson(info));
            });
            client.onClose(function () {
                console.log("onClose...");
            });
            client.onError(function (error) {
                console.log("error... " + error);
            });
        };

        this.send = function (info) {
            client.send(info);
        };
    }])
    .service('commonService', ['$uibModal', 'cookieFactory', function ($uibModal, cookieFactory) {
        console.log('common-service');

        // 创建分页查询
        this.createPageQuery = function (page, pageSize, maxPages) {
            var pageQuery = {
                page: page,// 当前页面序号
                pageSize: pageSize,// 页面大小
                pages: 0,// 页面数目
                pageNumbers: ['-', '+'],// 页面序号组
                maxPages: maxPages,// 最大显示页面数目
                data: [],// 数据数组
                setPage: function (page) {
                    if (page == '-') {
                        this.page--;
                        this.page = this.page >= 1 ? this.page : 1;
                    } else if (page == '+') {
                        this.page++;
                        this.page = this.page <= this.pages ? this.page : this.pages;
                    } else {
                        this.page = page;
                    }
                },
                catchResult: function (result) {
                    this.data = result.data;
                    this.page = result.edata.page;
                    this.pageSize = result.edata.pageSize;
                    this.pages = result.edata.pages;
                    this.pageNumbers.length = 0; // 清空页面序号组
                    /*
                     * 处理页面序号组
                     * TODO 这里可以优化
                     */
                    for (var i = 0; i < this.pages;) {
                        this.pageNumbers.push(++i);
                    }
                    // 如果( 页面数目>最大显示页面数目 )
                    if (this.pages > this.maxPages) {
                        /*
                         * 如果 (当前页面序号+最大显示页面数目-1) <= 页面数目
                         *
                         *  p s    pn    ps+pn
                         *   |-------------|
                         *   o             o
                         */
                        if ((this.page + this.maxPages - 1) <= this.pages) {
                            // 页面序号组=页面序号组[当前页面序号,当前页面序号+最大显示数目-1]
                            // slice [m,n) 左开右闭
                            this.pageNumbers = this.pageNumbers.slice(this.page - 1, this.page + this.maxPages - 1);
                        } else {
                            this.page = this.pages - this.maxPages;
                            this.pageNumbers = this.pageNumbers.slice(this.page, this.pages);
                        }
                    }
                    this.pageNumbers.splice(0, 0, '-');
                    this.pageNumbers.splice(this.pageNumbers.length, 0, '+');
                    this.pageNumbers.reverse();
                    console.log(this.pageNumbers);
                }
            };

            pageQuery.pageNumbers.reverse();
            return pageQuery;
        };

        // 打开Json编辑器
        this.openJsonEditor = function (title, json, close, dismiss) {
            var modalInstance = $uibModal.open({
                templateUrl: 'templates/template_json_editor.html',
                controller: 'TJsonEditorCtrl',
                backdrop: 'static',
                resolve: {
                    title: function () {
                        return title;
                    },
                    json: function () {
                        return json;
                    }
                }
            });

            modalInstance.result.then(function (json) {
                close(json);
            }, function () {
                dismiss();
            });
        };

        // 打开信息对话框
        this.openMessageDialog = function (title, content, submit, cancel) {
            var modalInstance = $uibModal.open({
                templateUrl: 'templates/template_message_dialog.html',
                controller: 'TMessageDialogCtrl',
                backdrop: 'static',
                resolve: {
                    title: function () {
                        return title;
                    },
                    content: function () {
                        return content;
                    }
                }
            });

            modalInstance.result.then(function () {
                submit();
            }, function () {
                cancel();
            });
        };

        function createToast() {
            var toast = {};
            var methods = ['info', 'error', 'success', 'warning'];

            angular.forEach(methods, function (x) {
                toast[x] = function (message, title) {
                    toastr[x](message, title);
                };
            });
            toastr.options = angular.extend({
                positionClass: 'toast-bottom-full-width'
            }, toast.options);
            toast.clear = toastr.clear;

            toast.putOToast = function (oToast) {
                cookieFactory.putOToast(oToast);
            };

            toast.showOToasts = function () {
                var oToasts = cookieFactory.getOToasts();
                angular.forEach(oToasts, function (oToast) {
                    toast[oToast['method']](oToast['info']);
                });
                oToasts.length = 0;
                cookieFactory.setOToasts(oToasts);
            };

            return toast;
        }

        this.toast = createToast();
    }])
    .service("templateService", ["$uibModal", "restService", "commonService", "app", function ($uibModal, restService, commonService, app) {
        this.resetPassword = function (username) {
            var modalInstance = $uibModal.open({
                templateUrl: 'templates/template_password_reset.html',
                controller: 'TPasswordResetCtrl',
                backdrop: 'static',
                resolve: {
                    params: {username: username}
                }
            });

            modalInstance.result.then(function (data) {
                restService.api.user.save({
                    ID: "resetPassword"
                }, {
                    username: data.username,
                    password: data.newPassword,
                    authCode: data.password
                }, function (result) {
                    if (app.catchResultCode(result['resultCode'])) {
                        commonService.toast.success("密码修改成功!");
                    }
                });
            }, function () {

            });
        };
    }])
    .run(['app', 'cookieFactory', '$rootScope', '$location', '$window', 'commonService', function (app, cookieFactory, $rootScope, $location, $window, commonService) {
        console.log('run');

        /*
         * app 配置
         */
        app.global.author = cookieFactory.getAuthor();
        app.global.online = app.global.author != null;
        app.routes = [];
        app.include_path = cookieFactory.getIncludePath();
        app.bombAttrs = cookieFactory.getBombAttrs();
        if (app.bombAttrs == null) {
            app.bombAttrs = {};
        }

        app.catchResultCode = function (code) {
            switch (code) {
                case 0x00:
                    return true;
                case 0x01:
                    commonService.toast.error('请求参数错误!');
                    return false;
                case 0x02:
                    commonService.toast.error('系统内部错误!');
                    return false;
                case 0x03:
                    commonService.toast.error('目标已存在错误!');
                    return false;
                case 0x07:
                    commonService.toast.error('信息验证错误!');
                    return false;
                case 0x09:
                case 0x0A:
                    app.setAuthor(null);
                    app.setOnline(false);
                    app.routes.length = 0;
                    window.location.href = '/login.html';
                    return false;

                default:
                    return false;
            }
        };

        app.getAuthor = function () {
            return app.global.author;
        };

        app.setOnline = function (online) {
            app.global.online = online;
        };

        app.getOnline = function () {
            return app.global.online;
        };

        /*
         * cookieFactory代理 start
         */
        app.setAuthor = function (author) {
            app.global.author = author;
            cookieFactory.setAuthor(author);
        };

        app.getRememberMe = function () {
            return cookieFactory.getRememberMe();
        };

        app.setRememberMe = function (rememberMe) {
            cookieFactory.setRememberMe(rememberMe);
        };

        app.setIncludePath = function (include_path) {
            app.include_path = include_path;
            cookieFactory.setIncludePath(include_path);
        };

        app.setBombAttrs = function (bombAttrs) {
            app.bombAttrs = bombAttrs;
            cookieFactory.setBombAttrs(bombAttrs);
        };
        // cookieFactory代理 end

        app.getCurUrl = function () {
            return app.global.cur_url;
        };

        app.setCurUrl = function (cur_url) {
            app.global.pre_url = app.global.cur_url;
            app.global.cur_url = cur_url;
        };


        /*
         * route 配置
         */
        $rootScope.$on('$locationChangeStart', function (evt, next, current) {
            var info = {
                name: '$locationChangeStart',
                next: next,
                current: current,
                time: new Date()
            };
            // console.log(angular.toJson(info, true));
        });

        $rootScope.$on('$locationChangeSuccess', function (evt, current, previous) {
            var info = {
                name: '$locationChangeSuccess',
                current: current,
                previous: previous,
                time: new Date()
            };
            // console.log(angular.toJson(info, true));
        });
    }]);